const app = getApp();

import { WEDDING_STATUS, SCENARIO, SCENARIOCLASSNAME, SHOW_COUNT } from '../../config';

import { getJoymewGiftsInfo, getUserSceneList, setJoymewGiftsChecked } from '../../api/user';
import { reqHasAddQyWeixin } from '@/api/scene';
import { storeBindingsBehavior } from 'mobx-miniprogram-bindings';
import { membershipStore } from '@/stores/membership-store';
import {
  isTodayShowedLevelUpBonusesPopup,
  setTodayShowedLevelUpBonusesPopup,
  isTodayPopAddQyFlag,
  setTodayPopAddQyFlag,
} from '../../utils/storage';
import { userStore } from '@/stores/user-store';

let currentPage = 1;
const showCount = SHOW_COUNT;
let totalPage = 1;
let loading = false;

Page({
  behaviors: [storeBindingsBehavior],
  storeBindings: [
    {
      store: userStore,
      fields: ['userInfo'],
      actions: ['getUserInfo'],
    },
    {
      store: membershipStore,
      fields: ['level', 'lastCheckGrade', 'levelBonusList'],
      actions: ['getMembershipBonusInfo'],
    },
  ],
  data: {
    token: app.globalData.token, //reLanuch 回来时这段代码赋值不生效
    scene_list: [],
    /** 用户等级 */
    userLevel: '1',
    /** 是否升级了 */
    isLevelUp: false,
    /** 要展示的升级奖励列表 */
    showLevelBonusList: [],
    /** 嗨喵豪礼相送弹窗的奖励列表 */
    joymewGiftBonusesList: [],
    // 进入场景 取值qyWeixin、''
    fromScene: '',
  },
  async onLoad(options) {
    this.setData({
      fromScene: options.fromScene || '',
    });
    await this.checkAndGetUserInfo();
    this.checkAndOpenPopup(); //进入小程序时弹窗检查出现逻辑
  },
  onShow() {
    if (app.globalData.homeNeedRefresh) {
      // 需要重新获取数据
      app.globalData.homeNeedRefresh = false;
      currentPage = 1;
      this.setData({
        scene_list: [],
        token: app.globalData.token,
      });
      loading = false;

      this.initSceneList();
      return;
    }
    currentPage = 1;
    this.setData({
      scene_list: [],
      token: app.globalData.token,
    });

    this.initSceneList();
  },
  /** 检查并获取数据 */
  async checkAndGetUserInfo() {
    let taskList = [];
    if (!this.data.userInfo.id) {
      taskList.push(this.getUserInfo());
    }
    await Promise.all(taskList);
    this.updateStoreBindings();
  },
  /** 打开十月巅峰赛活动「立即参与」弹窗 */
  openJoinNowPopup() {
    this.selectComponent('#joinNowPopup').open();
  },
  /** 打开「恭喜进阶」弹窗 */
  openCongratsLevelUpPopup() {
    this.selectComponent('#congratsLevelUpPopup').open();
  },
  /** 打开「升级奖励」弹窗 */
  openLevelUpBonusesPopup() {
    this.selectComponent('#levelUpBonusesPopup').open();
  },
  /** 打开「嗨喵豪礼相送」弹窗 */
  openJoymewGiftsPopup() {
    this.selectComponent('#joymewGiftsPopup').open();
  },
  // 打开企业红包弹窗
  // openEnterpriseRedPacketPopup() {
  //   this.selectComponent('#hbDialog').open();
  // },
  // 打开嗨喵福利官弹窗
  // openAddQyPopup() {
  //   this.selectComponent('#qyAddDialog').open();
  // },
  /** 点击「嗨喵豪礼相送」弹窗的「去查看」按钮 */
  handleJoymewGiftsPopupCheck() {
    this.selectComponent('#joymewGiftsPopup').close();
    getApp().globalData.hbtype = '2';
    wx.switchTab({
      url: '/pages/hb/hb',
    });
  },
  /** 进入小程序时弹窗检查出现逻辑 */
  async checkAndOpenPopup() {
    // 从企业微信点击卡片进入的场景
    // if (this.data.fromScene === 'qyWeixin') {
    //   this.openEnterpriseRedPacketPopup();
    //   return;
    // }
    // 添加嗨喵福利官相关逻辑
    // const hasAddQyRes = await reqHasAddQyWeixin();
    // 没加过微信并且今天没有弹出过
    // if (!hasAddQyRes.data && !isTodayPopAddQyFlag()) {
    //   setTodayPopAddQyFlag();
    //   this.openAddQyPopup();
    //   return;
    // }
    // 已经加过微信了 清空缓存
    // if (hasAddQyRes.data) {
    //   wx.removeStorageSync('addQyFlagShowedDate');
    // }
    // 请求嗨喵豪礼相送弹窗数据，如果需要弹窗，则弹窗
    const joymewGiftsInfoRes = await getJoymewGiftsInfo();
    if (joymewGiftsInfoRes.data.isNeedOpen === '1') {
      this.setData({
        joymewGiftBonusesList: joymewGiftsInfoRes.data.giftList.map((item) => ({
          icon: item.icon,
          name: item.name,
          rightContent: item.amount ? `¥${item.amount}` : '',
          validTimeText: item.validTimeText,
        })),
      });
      this.openJoymewGiftsPopup(); //打开「嗨喵豪礼相送」弹窗
      setJoymewGiftsChecked(); //保存「嗨喵豪礼相送」弹窗奖励为已领取状态
      return;
    }

    // 十月巅峰赛活动「立即参与」弹窗相关逻辑
    // const lastShowJoinNowPopupDate = wx.getStorageSync('lastShowJoinNowPopupDate');
    // const today = new Date().toLocaleDateString();
    // if (lastShowJoinNowPopupDate !== today) {
    //   this.openJoinNowPopup();
    //   wx.setStorageSync('lastShowJoinNowPopupDate', today);
    //   return;
    // }

    // 请求会员等级信息，根据不同情况弹窗
    if (!this.data.userInfo.isShowNewMembership) return;
    await this.getMembershipBonusInfo(); //获取并设置等级奖励相关信息
    this.updateStoreBindings();

    // 如果是第一次升到 11 级，弹出「恭喜进阶」弹窗
    if (this.data.lastCheckGrade < this.data.level && this.data.level === 10) {
      this.openCongratsLevelUpPopup();
      return;
    }

    // 弹出「升级奖励」弹窗相关逻辑
    if (isTodayShowedLevelUpBonusesPopup()) return;
    this.setData({
      isLevelUp: this.data.level > this.data.lastCheckGrade,
    });
    const filterLevelBonusList = this.data.isLevelUp
      ? this.data.levelBonusList.filter((item) => item.levelIndex > this.data.lastCheckGrade && item.levelIndex <= this.data.level)
      : this.data.levelBonusList.filter((item) => item.levelIndex === this.data.level + 1);

    this.setData({
      showLevelBonusList: filterLevelBonusList.map((item) => ({
        icon: item.icon,
        name: item.name,
        rightContent: item.amount ? `${item.amount}` : '',
        validTimeText: item.validTimeText,
      })),
    });

    this.openLevelUpBonusesPopup(); //打开「升级奖励」弹窗
    setTodayShowedLevelUpBonusesPopup(); //设置今天已经显示过升级奖励弹窗了
  },
  // 清除上次显示弹窗的日期
  clearLastShowedDate() {
    wx.showToast({
      title: '清除成功',
      icon: 'none',
    });
    wx.removeStorageSync('levelUpBonusesPopupShowedDate');
  },
  initSceneList() {
    if (loading) {
      return;
    }
    if (!this.data.token) {
      return;
    }

    loading = true;
    wx.showLoading({
      title: '加载中',
      mask: true,
    });
    // 获取当前用户的活动场次列表
    getUserSceneList({
      type: '5',
      showCount: showCount,
      currentPage: currentPage,
    })
      .then((res) => {
        const liveList = res?.data?.liveList || [];
        const targetLiveList = liveList.map((live) => {
          const { wedding_status, scenario } = live;
          let computedLiveProperty = {
            wedding_status_name: WEDDING_STATUS[wedding_status],
            scenario_name: SCENARIO[scenario] || SCENARIO['default'],
            scenario_class_name: SCENARIOCLASSNAME[scenario] || SCENARIOCLASSNAME['default'],
          };
          return {
            ...live,
            ...computedLiveProperty,
          };
        });
        if (targetLiveList && targetLiveList.length > 0) {
          this.setData({
            scene_list: this.data.scene_list.concat(targetLiveList),
          });
          // this.setData({
          //   token: app.globalData.token,
          // });
          totalPage = res.data.totalPage || 1;
          currentPage++;
        }
        loading = false;
        wx.hideLoading();
        wx.stopPullDownRefresh();
      })
      .catch((err) => {
        loading = false;
        wx.hideLoading();
        wx.stopPullDownRefresh();
      });
  },
  onReachBottom() {
    if (this.selectComponent('#showDialog').data.show) {
      // 引导遮罩中
      return;
    }

    if (currentPage > totalPage) {
      wx.showToast({
        title: '已经到底了',
        icon: 'none',
      });
      return;
    }

    this.initSceneList();
  },
  showPCEnter() {
    this.selectComponent('#showDialog').display();
  },
  /**
   * 申请活动
   */
  toApplyActivity() {
    wx.navigateTo({
      url: '/pages/index/applyActivity/applyActivity',
    });
  },
  /**
   * 跳转到AI助手
   */
  toCopilot() {
    wx.navigateTo({
      url: '/subpkgActivity/pages/copilot/index',
    });
  },
  onPullDownRefresh() {
    currentPage = 1;
    totalPage = 1;
    this.setData({
      scene_list: [],
      token: app.globalData.token,
    });
    this.initSceneList();
    this.checkAndOpenPopup();
  },
  handleAuthSuccess() {
    // 需要重新获取数据
    app.globalData.homeNeedRefresh = false;
    currentPage = 1;
    this.setData({
      scene_list: [],
      token: app.globalData.token,
    });
    loading = false;

    this.initSceneList();
  },
});
